import React from 'react';
import { withRouter } from 'react-router-dom';
import { PullToRefresh, ActivityIndicator } from 'weaver-mobile';
import '../../style/dragula.css';
import Dragula from 'react-dragula';
import { getRouteParams, cssFilter } from '../../util';
import * as API_HOMEPAGE from '../../apis/homepage';
// 加载状态组件
import Loading from './Loading';
// 流程中心元素
import Workflow from './elements/workfow';
// 文档中心元素
import Doc from './elements/doc';
// 自定义页面元素
import CustomPage from './elements/custompage';
// 图表元素
import Chart from './elements/chart';
// 手机图片元素
import Slide from './elements/slide';
// 待办统计元素
import TodoCount from './elements/todocount';
// 自定义元素
import CustomElement from './elements/customelement';
// 移动快捷入口
import MobileQuickEntry from './elements/quickenter';
// 排行榜元素
import RankingList from './elements/rankinglist';
//时间轴元素
import MobileTimeLine from './elements/timeline';

@withRouter
class Homepage extends React.Component {
  constructor(props) {
    super(props);
    this.onLoadData = this.onLoadData.bind(this);
    this.onRefresh = this.onRefresh.bind(this);
    this.onSetting = this.onSetting.bind(this);
    this.onMove = this.onMove.bind(this);
    this.onDelete = this.onDelete.bind(this);
    this.onReload = this.onReload.bind(this);
    this.onShrink = this.onShrink.bind(this);
    window.onReload = this.onReload.bind(this);
    window.onShrink = this.onShrink.bind(this);
    this.state = {
      loading: false,
      refreshing: false,
      hpid: 0,
      subCompanyId: 0,
      areaElements: [],
      hpCss: ''
    };
  }

  componentWillMount() {
    const params = getRouteParams(this.props);
    this.onLoadData(params);
  }

  componentWillReceiveProps(nextProps) {
    const oldParams = getRouteParams(this.props);
    const params = getRouteParams(nextProps);

    if (oldParams.hpid != params.hpid || oldParams.subCompanyId != params.subCompanyId) {
      this.onLoadData(params);
    }
  }

  componentDidUpdate() {
    const { isSetting } = this.props;
    isSetting && Dragula([this.refs['items']]).on('dragend', () => this.onMove());
  }

  render() {
    const { isSetting, navbarHeight } = this.props;
    const { loading, refreshing, hpid, subCompanyId, areaElements, hpCss } = this.state;

    return (
      <div className="homepage" style={{ top: navbarHeight }}>
        <style dangerouslySetInnerHTML={{ __html: hpCss }} />
        <div className="homepage-content">
          <PullToRefresh
            style={{ height: '100%', overflow: 'auto' }}
            direction="down"
            damping={60}
            refreshing={refreshing}
            onRefresh={this.onRefresh}
            indicator={{ release: <ActivityIndicator text="loading..." /> }}
          >
            <Loading loading={loading}>
              <div ref="items" className={`items ${isSetting ? 'items-setting' : ''}`}>
                {areaElements.map(item => {
                  const { eid, ebaseid } = item.item;
                  const { title, isshow } = item.header;
                  const params = { ...item, refreshing, hpid, subCompanyId, eid, ebaseid };

                  let content = null;
                  if (/^Custom_/.test(ebaseid)) {
                    content = <CustomElement {...params} />
                  } else {
                    switch (ebaseid) {
                      case '7':
                        content = <Doc {...params} />;
                        break;
                      case '8':
                        content = <Workflow {...params} />;
                        break;
                      case '29':
                        content = <CustomPage {...params} />;
                        break;
                      case 'reportForm':
                        content = <Chart {...params} />;
                        break;
                      case 'mobilePicture':
                        content = <Slide {...params} />;
                        break;
                      case 'todoCount':
                        content = <TodoCount {...params} />;
                        break;
                      case 'mobileQuickEntry':
                        content = <MobileQuickEntry {...params} />;
                        break;
                      case 'RankingList':
                        content = <RankingList {...params} />;
                        break;
                        case 'timeLine':
                            content=<MobileTimeLine {...params} />;
                            break;
                    }
                  }

                  return (
                    <div
                      id={`item_${eid}`}
                      className="item"
                      data-eid={eid}
                      data-ebaseid={ebaseid}
                      style={ebaseid == 'mobilePicture' ? { marginBottom: 0 } : {}}
                      onClick={e => isSetting && this.onSetting(e, eid, ebaseid)}
                    >
                      {(isSetting || isshow != 'false') && (
                        <div className="header" style={{ display: 'block' }}>
                          <div className="title">{title}</div>
                          {isSetting && <div className="close" onClick={e => this.onDelete(e, eid)} />}
                        </div>
                      )}
                      {content}
                    </div>
                  );
                })}
              </div>
            </Loading>
          </PullToRefresh>
        </div>
      </div>
    );
  }

  onLoadData(params, callback) {
    const { hpid, subCompanyId } = params;

    this.setState({ loading: true, hpid, subCompanyId });
    API_HOMEPAGE.getHomepageData({ hpid, subCompanyId }).then(result => {
      let { areaElements = [], hpCss = '' } = result;
      hpCss = cssFilter(hpCss);
      this.setState({ loading: false, areaElements, hpCss });
      callback && typeof callback == 'function' && callback();
    });
  }

  onRefresh() {
    const { hpid, subCompanyId } = this.state;

    this.setState({ refreshing: true });
    API_HOMEPAGE.getHomepageData({ hpid, subCompanyId }).then(result => {
      window.setTimeout(() => {
        let { areaElements = [], hpCss = '' } = result;
        hpCss = cssFilter(hpCss);
        this.setState({ refreshing: false, areaElements, hpCss });
      }, 500);
    });
  }

  onSelect(eid) {
    const items = document.querySelectorAll('.items .item');
    for (let i = 0, len = items.length; i < len; i++) {
      if (items[i].getAttribute('data-eid') == eid) {
        items[i].setAttribute('class', 'item active');
      } else {
        items[i].setAttribute('class', 'item');
      }
    }
  }

  onSetting(e, eid, ebaseid) {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();

    this.onSelect(eid);
    window.parent.onMESetting(eid, ebaseid);
  }

  onMove() {
    const items = document.querySelectorAll('.items .item');
    const eids = [];
    for (let i = 0, len = items.length; i < len; i++) {
      let eid = items[i].getAttribute('data-eid');
      eids.push(eid);
    }

    const { hpid, subCompanyId } = this.state;
    window.parent.onMESort(hpid, subCompanyId, eids.join(','));
  }

  onDelete(e, eid) {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();

    let eids = '';
    const items = document.querySelectorAll('.items .item');
    for (let i = 0, len = items.length; i < len; i++) {
      const _eid = items[i].getAttribute('data-eid');
      if (_eid != eid) {
        eids += _eid + ',';
      }
    }

    window.parent.onMEDelete(eid, eids);
  }

  onReload(hpid, subCompanyId, eid, callback) {
    this.onLoadData({ hpid, subCompanyId }, () => {
      this.onSelect(eid);
      callback && typeof callback == 'function' && callback();
    });
  }

  onShrink(isShrink) {
    const items = document.querySelectorAll('.items .item .content');
    for (let i = 0, len = items.length; i < len; i++) {
      items[i].style.display = isShrink ? 'none' : 'block';
    }
  }
}

export default Homepage;
